#!/usr/bin/python3
import os
from .Entity import Entity
from utils import My_Util2


class Service_Broker:
    """
    业务接口经纪人类
    """

    def __init__(self, context, entity: Entity) -> None:
        self.context = context
        self.entity = entity
        self.my_util2 = My_Util2.My_Util(self.context)

    def code_includes(self):
        """
        包引入
        """
        package = self.entity.package
        prefix = self.entity.table_name.split("_")[0].lower()
        entity_name = self.entity.name
        includes = list()

        includes.append(
            f"""import {package}.internal.broker.{entity_name}ServiceBaseBroker;"""
        )
        includes.append(f"""import {package}.{prefix}.service.I{entity_name}Service;""")
        includes.append(f"""import org.springframework.context.annotation.Lazy;""")
        includes.append(f"""import org.springframework.stereotype.Component;""")
        includes = self.my_util2.sort_import_order(includes)
        return "\r".join(includes)

    def save_file(self, dir):
        prefix = self.entity.prefix
        _target_dir = os.path.join(dir, prefix, "broker")
        if not os.path.exists(_target_dir):
            os.makedirs(_target_dir)
        with open(
            os.path.join(_target_dir, "{}ServiceBroker.java".format(self.entity.name)),
            mode="w",
            encoding="utf-8",
        ) as f:
            f.write(self.code())

    def code(self):
        author = self.entity.author
        package = self.entity.package
        entity_name = self.entity.name
        prefix = self.entity.prefix
        object_name = entity_name[:1].lower() + entity_name[1:]
        comment = self.entity.comment

        includes = self.code_includes()

        return f"""package {package}.{prefix}.broker;

{includes}

/**
 * <p>
 * {comment}业务接口经纪人类
 * </p>
 *
 * @author {author}
 */
@Component
public class {entity_name}ServiceBroker extends {entity_name}ServiceBaseBroker {'{'}

    public {entity_name}ServiceBroker(@Lazy final I{entity_name}Service {object_name}Service) {"{"}
        super({object_name}Service);
    {"}"}
{'}'}
"""
